package com.symaster.common.animation;

import com.symaster.common.geom.entity.LineSegment;
import com.symaster.common.geom.entity.Point;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinmiao
 * @version 2023/11/2
 */
public class CurveUtil {
    public static List<LineSegment> getBezierLines(CurvePoint[] curvePoints) {

        List<LineSegment> lineSegments = new ArrayList<>();

        List<Point> points = new ArrayList<>();
        for (float t = 0; t < 1; t += 0.002f) {
            CurvePoint p1 = cubicBezier(t, curvePoints);
            CurvePoint p2 = cubicBezier(t + 0.001f, curvePoints);
            points.add(new Point(p1.getX(), p1.getY()));
            points.add(new Point(p2.getX(), p2.getY()));
        }

        for (int i = 0; i < points.size() - 1; i++) {
            Point p1 = points.get(i);
            Point p2 = points.get(i + 1);
            lineSegments.add(new LineSegment(p1, p2));
        }

        return lineSegments;
    }

    private static CurvePoint cubicBezier(float t, CurvePoint[] p) {
        CurvePoint[] temp = new CurvePoint[p.length];
        System.arraycopy(p, 0, temp, 0, p.length);


        for (int i = 0; i < p.length - 1; i++) {
            for (int j = 0; j < p.length - i - 1; j++) {
                float x = (1 - t) * temp[j].getX() + t * temp[j + 1].getX();
                float y = (1 - t) * temp[j].getY() + t * temp[j + 1].getY();
                temp[j] = new CurvePoint(x, y);
            }
        }
        return temp[0];
    }

}
